//
//  BLServerConfig.m
//  BasketBallLeagues
//
//  Created by kenshin on 4/24/17.
//  Copyright © 2017 kenshin. All rights reserved.
//

#import "BLServerConfig.h"

@interface BLServerConfig ()

@property (nonatomic, strong) NSString *baseUrl; ///< 请求基地址

@end

@implementation BLServerConfig

+ (instancetype)sharedInstance
{
    static BLServerConfig *singleOjbect = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        singleOjbect = [[self alloc] init];
    });
    return singleOjbect;
}

- (instancetype)init
{
    if (self = [super init]) {
        _isOnline = [[NSUserDefaults standardUserDefaults] boolForKey:kUDServerAPIOnline];
        
        if ([self isDebug]) {
            _isOnline = NO;
        }
        
        [self loadServerPlist];
    }
    return self;
}


- (BOOL)isDebug
{
#ifdef DEBUG
    return NO;
#else
    return NO;
#endif
}

- (NSString *)appVersion
{
    return [[self infoDictionary] objectForKey:@"CFBundleShortVersionString"];
}

- (NSString *)appName
{
    return [[self infoDictionary] objectForKey:@"CFBundleDisplayName"];
}

- (void)updateServerAPIOnline:(BOOL)isOnline {
    self.isOnline = isOnline;
    [[NSUserDefaults standardUserDefaults] setBool:isOnline forKey:kUDServerAPIOnline];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
    [self loadServerPlist];
}

#pragma mark -

- (void)loadServerPlist
{
    NSString *filepath = [[NSBundle mainBundle] pathForResource:@"server" ofType:@"plist"];
    NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:filepath];
    self.baseUrl = self.isOnline ? dict[@"baseUrl_online"] : dict[@"baseUrl_test"];
}

/// 请求地址区分正式环境和测试环境
- (NSString *)urlWithStr:(NSString *)str
{
    if (!self.isOnline) {
//        return [str stringByReplacingCharactersInRange:[str rangeOfString:@"api."] withString:@"apitest."];
    }
    return str;
}

- (NSDictionary *)infoDictionary
{
    static NSDictionary *_infoDictionary;
    if (!_infoDictionary) {
        _infoDictionary = [[NSBundle mainBundle] infoDictionary];
    }
    return _infoDictionary;
}

@end
